const DB = require('../../utils/db');
const { ipv6ToV4, getDateTime } = require('../../utils/utlis');

const IP2Region = require('ip2region').default;
const query = new IP2Region();

const eventEmitter = require('../../utils/events');

module.exports = {
	add: async (ipv6, userId) => {
		// ipv6转ipv4
		let ip = ipv6ToV4(ipv6);

		const { country, province, city, isp } = query.search(ipv6);
		let data = {};

		// 当前游客是不是 用户
		if (userId) {
			// 用户
			let [arr] = await DB.query(`select *,date_format(login_time,'%Y-%m-%d %H:%i:%s') loginTime from t_user where id=? and type=1`, [userId]);

			data = {
				avatar: arr[0].avatar,
				username: arr[0].username,
				ip,
				time: arr[0].loginTime,
				address: country + province + city,
				isp
			};

			await DB.query('update t_visitor set count=count+1,userId=? where ip=? and type=1', [userId, ip]);
		} else {
			data = {
				avatar: '/uploads/avatar/nv.png',
				username: '游客',
				ip,
				time: getDateTime(new Date().getTime())[6],
				address: country + province + city,
				isp
			};
			// 游客
			let [list] = await DB.query('select *  from t_visitor where ip=? and type=1', [ip]);
			if (list.length) {
				await DB.query('update t_visitor set count=count+1 where ip=? and type=1', [ip]);
			} else {
				await DB.query('insert into t_visitor (ip,ipv6,country,province,city,isp,type,count) values(?,?,?,?,?,?,1,1)', [ip, ipv6, country, province, city, isp]);
			}
		}

		// 登录的用户 发送sse
		eventEmitter.emit('online', data);
	}
};
